package com.bls.cate.adapter;

import android.app.Activity;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bls.cate.R;
import com.bls.cate.bean.HomeBean;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class HomeBottomBarAdapter extends BaseQuickAdapter<HomeBean.BottomBarBean, HomeBottomBarAdapter.ViewHolder> {

    private OnBottomBarClickListener onBottomBarClickListener;

    public HomeBottomBarAdapter(@Nullable List<HomeBean.BottomBarBean> data) {
        super(R.layout.view_home_bottom_bar, data);
    }

    @Override
    protected void convert(final ViewHolder helper, final HomeBean.BottomBarBean item) {
        final int position = helper.getLayoutPosition();
        helper.tvText.setText(item.getText());
        helper.ivImage.setImageResource(item.isSelect() ? item.getSelectImage() : item.getUnSelectImage());
        helper.rlItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != onBottomBarClickListener) {

                    int oldPosition = getOldSelectPosition();

                    if (position == oldPosition) return;

                    changeBottomBarState(oldPosition, position);

                    onBottomBarClickListener.onBottomBarClick(position);
                }
            }
        });
    }

    private void changeBottomBarState(int oldPosition, int position) {
        mData.get(oldPosition).setSelect(false);
        mData.get(position).setSelect(true);
        notifyDataSetChanged();
    }

    private int getOldSelectPosition() {
        int oldPosition = 0;
        for (int i = 0, j = mData.size(); i < j; i++) {
            if (mData.get(i).isSelect()) {
                oldPosition = i;
                break;
            }
        }
        return oldPosition;
    }


    public void setOnBottomBarClickListener(OnBottomBarClickListener onBottomBarClickListener) {
        this.onBottomBarClickListener = onBottomBarClickListener;
    }

    public interface OnBottomBarClickListener {
        void onBottomBarClick(int position);
    }


    class ViewHolder extends BaseViewHolder {
        @BindView(R.id.iv_image)
        ImageView ivImage;
        @BindView(R.id.tv_text)
        TextView tvText;
        @BindView(R.id.rl_item)
        RelativeLayout rlItem;

        public ViewHolder(View view) {
            super(view);
            ButterKnife.bind(this, view);
        }
    }
}
